﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using FileManagerGlobal_Library;
using FileManager_Server.ServiceModel.Client_Update_Model.Client_Update_DataTransfer_Model;
using FileManager_Server.ServiceModel.DataTransfer_Model;
using FileManager_Server.ServiceModel.WCF_Args_Model;
using FileManager_Server.Utility;
using System.Windows.Forms;

namespace FileManager_Server.BusinessLogic.WCF.Client_Update_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Client_UpdateService" in both code and config file together.
    public class Client_UpdateService : IClient_UpdateService
    {

        public UpdateFileInfo CheckClientUpdateInfo()
        {
            var result = new UpdateFileInfo();
            try
            {
                result.FileName = GlobalVariable.ClientAppVariable.ClientUpdateFileName;
                var applicationInfo = ServerLocalFile.ReadApplicationInfo();
                if (null != applicationInfo)
                {
                    result.ApplicationVersion = applicationInfo.ClientVersion;
                    var updatePath = Path.Combine(Application.StartupPath,
                                              GlobalString.System_Config_String.ClientUpdatePath);
                    var fileInfo = new FileInfo(updatePath);
                    result.FileLength = fileInfo.Length;
                    result.UpdateInfomation = applicationInfo.Infomation;
                }
                else
                    result.UpdateError = UpdateError.NotFindFile;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CheckClientUpdateInfo has problem", ex);
                result.UpdateError = UpdateError.ServerHasProblem;
            }
            return result;
        }

        public DownloadingResult DownloadClientUpdate(FileDownloadingArgs fileDownloadingArgs)
        {
            try
            {
                var result = new DownloadingResult { DataTransfer = new byte[fileDownloadingArgs.DataLength] };
                var updatePath = Path.Combine(Application.StartupPath,
                                              GlobalString.System_Config_String.ClientUpdatePath);
                using (var fileStream = new FileStream(updatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStream.Position = fileDownloadingArgs.Offset;
                    fileStream.Read(result.DataTransfer, 0, result.DataTransfer.Length);
                }
                return result;
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("DownloadClientUpdate has problem", ex);
                throw;
            }
        }
    }
}
